//
//  WHShopNameController.m
//  SquirrelCourier
//
//  Created by 邓伟浩 on 2019/1/4.
//  Copyright © 2019 邓伟浩. All rights reserved.
//

#import "WHShopNameController.h"
#import "UIView+YBInputControl.h"
#import "JFCityViewController.h"
#import "WHRootNavigationController.h"
#import "JFLocation.h"
#import "WHStationNameModel.h"

@interface WHShopNameController ()<UITableViewDelegate, UITableViewDataSource, JFCityViewControllerDelegate>

@property (nonatomic, strong) UITableView *dataTableView;

@property (nonatomic, strong) NSURLSessionDataTask *dataTask;
@property (nonatomic, strong) UILabel *cityLabel;
@property (nonatomic, strong) UIView *searchHeaderView;

@property (nonatomic, strong) JFLocation *locationManager;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;

@property (nonatomic, copy) NSString *searchCity;
@property (nonatomic, copy) NSString *stationName;

@end

@implementation WHShopNameController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"门店名称";
    [self initParams];
    [self setUpSearhHeaderView];
    [self setUpTableView];
    
}

- (void)initParams {
    _page = 1;
    _dataArray = @[].mutableCopy;
}

- (void)setUpTableView {
    UITableView *dataTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    dataTableView.delegate = self;
    dataTableView.dataSource = self;
    [self.view addSubview:dataTableView];
    
    [dataTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    
    dataTableView.tableFooterView = [UIView new];
    dataTableView.backgroundColor = CViewBgMainColor;
    dataTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    dataTableView.separatorColor = CLineColor;
    
    [dataTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(_searchHeaderView.mas_bottom);
    }];
    
    kWeakSelf(self);
    dataTableView.mj_header = [WHGifHeader headerWithRefreshingBlock:^{
        [weakself headerRereshing];
    }];
    
    dataTableView.mj_footer = [WHGifFooter footerWithRefreshingBlock:^{
        [weakself footerRereshing];
    }];
    dataTableView.mj_header.hidden = YES;
    dataTableView.mj_footer.hidden = YES;
    
    _dataTableView = dataTableView;
}

- (void)headerRereshing {
    [self getResultByPageNumber:1 completion:^(BOOL isSucess, BOOL isLast) {
        [self.dataTableView.mj_header endRefreshing];
        if (isSucess) {
            _page = 1;
            self.dataTableView.mj_footer.hidden = NO;
            self.dataTableView.mj_header.hidden = NO;
            if (isLast) {
                self.dataTableView.mj_footer.hidden = YES;
                self.dataTableView.mj_header.hidden = YES;
            } else {
                [self.dataTableView.mj_footer resetNoMoreData];
            }
        }
    }];
}

- (void)footerRereshing {
    [self getResultByPageNumber:(_page+1) completion:^(BOOL isSucess, BOOL isLast) {
        if (isSucess) {
            if (isLast) {
                [self.dataTableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                _page = _page + 1;
                [self.dataTableView.mj_footer endRefreshing];
            }
            
        } else {
            [self.dataTableView.mj_footer endRefreshing];
        }
        
    }];
    
}

- (void)setUpSearhHeaderView {
    UIView *tableHeaderView = [[UIView alloc] init];
    tableHeaderView.backgroundColor = KWhiteColor;
    [self.view addSubview:tableHeaderView];
    _searchHeaderView = tableHeaderView;
    [tableHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(kRealwidth(55));
        make.top.equalTo(@kTopHeight);
    }];
    
    UIView *citySelectView = [[UIView alloc] init];
    [tableHeaderView addSubview:citySelectView];
    [citySelectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(tableHeaderView.mas_left).offset(kRealwidth(15));
        make.height.mas_equalTo(kRealwidth(55));
        make.centerY.mas_equalTo(tableHeaderView.mas_centerY);
        make.width.mas_equalTo(kRealwidth(100));
    }];
    
    UILabel *cityLabel = [[UILabel alloc] init];
    [citySelectView addSubview:cityLabel];
    cityLabel.textColor = CFontTitleBlackColor;
    cityLabel.text = @"请选择城市";
    cityLabel.adjustsFontSizeToFitWidth = YES;
    cityLabel.font = SYSTEMFONT(kRealwidth(16));
    [cityLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(citySelectView.mas_left);
        make.centerY.mas_equalTo(citySelectView.mas_centerY);
        make.height.mas_equalTo(kRealwidth(16));
        make.width.mas_equalTo(kRealwidth(70));
    }];
    _cityLabel = cityLabel;
    
    UIImageView *tipsImageView = [[UIImageView alloc] init];
    [citySelectView addSubview:tipsImageView];
    tipsImageView.image = IMAGE_NAMED(@"shop_selectCity_icon");
    [tipsImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kRealwidth(18));
        make.height.mas_equalTo(kRealwidth(10));
        make.left.mas_equalTo(cityLabel.mas_right);
        make.centerY.mas_equalTo(citySelectView.mas_centerY);
    }];
    
    UIView *gapView1 = [[UIView alloc] init];
    [tableHeaderView addSubview:gapView1];
    gapView1.backgroundColor = CLineColor;
    [gapView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(kRealwidth(16));
        make.width.mas_equalTo(1);
        make.left.mas_equalTo(citySelectView.mas_right);
        make.centerY.mas_equalTo(tableHeaderView.mas_centerY);
    }];
    
    UITextField *nameField = [[UITextField alloc] init];
    nameField.font = SYSTEMFONT(kRealwidth(16));
    nameField.textColor = CFontTitleBlackColor;
    [tableHeaderView addSubview:nameField];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入门店名称" attributes:@{NSForegroundColorAttributeName:CFontContentLightGrayColor, NSFontAttributeName:nameField.font}];
    nameField.attributedPlaceholder = attrString;
    [nameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(gapView1.mas_right).offset(kRealwidth(15));
        make.right.mas_equalTo(tableHeaderView.mas_right).offset(-kRealwidth(15));
        make.centerY.mas_equalTo(tableHeaderView.mas_centerY);
        make.height.mas_equalTo(kRealwidth(55));
    }];
        kWeakSelf(self);
    nameField.yb_inputCP = YBInputControlProfile.creat.set_maxLength(30).set_textChanged(^(id obj) {
        NSString *searchText = [obj valueForKey:@"text"];
        DLog(@"搜索文本: %@", searchText);
        _stationName = searchText;
        [weakself headerRereshing];
    });
    [nameField becomeFirstResponder];
    
    UIView *gapView = [[UIView alloc] init];
    gapView.backgroundColor = CLineColor;
    [tableHeaderView addSubview:gapView];
    [gapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(tableHeaderView);
        make.bottom.mas_equalTo(tableHeaderView.mas_bottom);
        make.height.mas_equalTo(0.5);
    }];
    
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectCity)];
    [citySelectView addGestureRecognizer:tapGes];
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
    cell.textLabel.font = SYSTEMFONT(kRealwidth(16));
    cell.textLabel.textColor = CFontTitleBlackColor;
    WHStationNameModel *nameModel = self.dataArray[indexPath.row];
    cell.textLabel.text = nameModel.stationName;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(55);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WHStationNameModel *nameModel = self.dataArray[indexPath.row];
    
    if (self.selectShopName) {
        self.selectShopName(nameModel);
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)selectCity {
    JFCityViewController *cityViewController = [[JFCityViewController alloc] init];
    cityViewController.delegate = self;
    cityViewController.title = @"城市选择";
    WHRootNavigationController *navigationController = [[WHRootNavigationController alloc] initWithRootViewController:cityViewController];
    [self presentViewController:navigationController animated:YES completion:nil];
}

- (void)cityName:(NSString *)name {
    _cityLabel.text = name;
    _searchCity = name;
    [self headerRereshing];
}

#pragma mark —————— 接口 ——————

- (void)getResultByPageNumber:(int)pageNumber completion:(void (^)(BOOL isSucess, BOOL isLast))completion {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_selectstation);
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          self.searchCity?:@"", @"city",
                          @(pageNumber), @"pageNum",
                          self.stationName, @"stationName",
                          nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *errCode = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (errCode.intValue == 0) {
                NSDictionary *object = responseObject[@"retobj"];
                
                if (pageNumber == 1) {
                    [_dataArray removeAllObjects];
                }
                
                NSArray *stations = object[@"data"];
                if (stations.count == 0) {
                    if (completion) {
                        [self.dataTableView reloadData];
                        completion(YES, YES);
                    }
                    return;
                }
                
                NSArray *tempStationArray = [NSArray modelArrayWithClass:[WHStationNameModel class] json:stations];
                [self.dataArray addObjectsFromArray:tempStationArray];
                [self.dataTableView reloadData];
                
                if (completion) {
                    completion(YES, NO);
                }
                
            } else {
                [WHView showMessage:errorMsg inView:self.view];
                if (completion) {
                    completion(NO, NO);
                }
            }
        }
    } failure:^(NSError *error) {
        if (completion) {
            completion(NO, NO);
        }
    }];
}

- (void)backBtnClicked {
    [super backBtnClicked];
    if (_dataTask) {
        [_dataTask cancel];
        _dataTask = nil;
    }
}

@end
